<?php

namespace addons\exam\controller;

use addons\exam\enum\CateUses;
use addons\exam\enum\CommonStatus;
use addons\exam\model\CateOrderModel;
use addons\exam\model\CateUserLogModel;
use addons\exam\model\QuestionModel;
use addons\exam\model\UserModel;
use app\admin\model\exam\CateModel;
use app\admin\model\exam\QuestionCollectModel;
use app\admin\model\exam\QuestionWrongModel;
use app\admin\model\exam\UserInfoModel;


/**
 * 试题接口
 */
class Question extends Base
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 看题模式
     */
    public function lookPage()
    {
        $model = new QuestionModel();
        $total = $model->where('cate_id', $this->request->param('cate_id'))->count('id');
        $this->success('', compact('total'));
    }

    /**
     * 练习模式
     */
    public function train()
    {
        $param            = $this->request->param();
        $param['user_id'] = $this->auth->id;

        // 验证是否需要绑定手机号
        UserModel::isMustBindMobile($this->auth->getUser());

        if (!input('just_get_count/d', 0)) {
            if (($cate_id = input('cate_id/d')) && ($cate = CateModel::get($cate_id))) {
                $orderInfo = CateOrderModel::where(['user_id'=>$this->auth->id,'cate_id'=>$cate_id,'status'=>1])->find();
                if(!$orderInfo){
                    $UserInfo = UserInfoModel::where(['user_id'=>$this->auth->id])->find();
                    if($UserInfo){
                        if(time() > $UserInfo['expire_time']){
                            $this->error('该题目类型仅针对会员开放，请开通会员后再试');
                        }
                    }else{
                        $this->error('该题目类型仅针对会员开放，请开通会员后再试');
                    }
                }

//                if ($cate['uses'] == CateUses::ONLY_MEMBER && !UserModel::isMember($this->auth->id)) {
//                    $this->error('该题目类型仅针对会员开放，请开通会员后再试');
//                }
//                if (!$cate['is_free'] && $cate['price'] > 0) {
//                    if (!CateUserLogModel::isOpenCate($this->auth->id, $cate_id)) {
//                        $this->error('该题库需要付费开通，请先购买后再试', ['need_open' => true, 'cate' => $cate]);
//                    }
//                }
            }
        }

        $list = QuestionModel::getList($param);
        $this->success('', $list);
    }

    /**
     * 根据关键词模糊查询10条题目
     */
    public function search()
    {
        $query = \addons\exam\model\QuestionModel::with(
            [
                'cates' => function ($query) {
                    $query->field('id,name');
                },
            ]
        )->where('status', CommonStatus::NORMAL);

        if ($keyword = input('keyword/s', '', 'trim,strip_tags,htmlspecialchars,xss_clean')) {
            if (mb_strlen($keyword) < 2) {
                $this->error('请输入不少于2个字的关键词进行搜索');
            }

            $query->where('title', 'like', '%' . $keyword . '%');
        }

        if ($sort_type = input('sort_type/s')) {
            $query->order($sort_type);
        }

        if (input('sort_rand/d', 0)) {
            $query->orderRaw('rand()');
        }

        $list = $query->paginate(15, true)->toArray();
        // 最多搜索5页
        if (input('page/d') >= 5) {
            $list['has_more'] = false;
        }

        $this->success('', ['list' => $list]);
    }

    /**
     * 试题详情
     */
    public function detail($id)
    {
        $this->success('', (new QuestionModel)->get($id));
    }

    /**
     * 收藏列表
     */
    public function collectList()
    {
        $user_id         = $this->auth->id;
        $collectQuestion = new QuestionCollectModel();
        $list            = $collectQuestion::with('question')->where('user_id', $user_id)->order('id desc')->paginate(999, true);
        $total           = $collectQuestion::where('user_id', $user_id)->count();

        $this->success('', compact('list', 'total'));
    }

    /**
     * 添加收藏
     */
    public function collectAdd()
    {
        if (!$question_id = input('question_id/d', 0)) {
            $this->error('缺少题目ID');
        }
        if (!QuestionModel::where('id', $question_id)->count()) {
            $this->error('题目数据不存在');
        }

        if ($res = QuestionCollectModel::updateOrCreate(
            [
                'user_id'     => $this->auth->id,
                'question_id' => $question_id
            ],
            [
                'user_id'     => $this->auth->id,
                'question_id' => $question_id,
                'user_answer' => input('user_answer','')
            ])
        ) {
            $this->success('收藏成功', $res);
        }
        $this->error('收藏失败');
    }

    /**
     * 取消收藏
     */
    public function collectCancel()
    {
        if (!$question_id = input('question_id/d', 0)) {
            $this->error('缺少题目ID');
        }
        $result = QuestionCollectModel::where('question_id', $question_id)->where('user_id', $this->auth->id)->delete();

        if ($result) {
            $this->success('取消成功');
        }
        $this->error('取消失败');
    }

    /**
     * 获取错题列表
     */
    public function wrongList()
    {
        $user_id = $this->auth->id;
        $cate_id = input('cate_id');
        $where['user_id'] = $user_id;
        if($cate_id){
            $where['ca_id'] = $cate_id;
        }
        if ($ids = input('question_ids')) {
            $total = QuestionWrongModel::where($where)->whereIn('question_id', $ids)->count();
            $list  = $total ? QuestionWrongModel::with('question')
                ->whereIn('question_id', $ids)
                ->where($where)
                ->order('id desc')
                ->paginate(999, true)->toArray() : [];
        } else {
            $total = QuestionWrongModel::where($where)->count();
            $list  = $total ? QuestionWrongModel::with('question')
                ->where($where)
                ->order('id desc')
                ->paginate(999, true)->toArray() : [];
        }
        if (isset($list['data']) && $list['data']) {
            $questions = [];
            foreach ($list['data'] as $item) {
                if(!$item['user_answer']){
                    $item['user_answer'] = db('exam_question_wrong')->where(['id'=>$item['id']])->value('user_answer');
                }
                $questions[] = array_merge($item['question'], ['wrong_id' => $item['id'], 'user_answer' => $item['user_answer']]);
            }
            $list['data'] = \addons\exam\model\QuestionModel::isCollected($user_id, $questions);
        } else {
            $list['data'] = [];
        }

        $this->success('', compact('list', 'total'));
    }

    /*
     * 记录错题
     */
    public function wrongAdd()
    {
        if (!$question_id = input('question_id/d', 0)) {
            $this->error('缺少题目ID');
        }
        $cate_id = \addons\exam\model\QuestionModel::where(['id'=>$question_id])->value('cate_id');
        if (QuestionWrongModel::add($this->auth->id, $question_id,$cate_id))
            $this->success('记录成功');
        else
            $this->error('记录失败');
    }

    /**
     * 删除错题
     */
    public function wrongDelete()
    {
        if (!$question_id = input('question_id/d', 0)) {
            $this->success('缺少错题ID');
        }

        if (QuestionWrongModel::where('question_id', $question_id)->where('user_id', $this->auth->id)->delete()) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    /**
     * 清空所有错题
     */
    public function wrongClear()
    {
        if (QuestionWrongModel::where('user_id', $this->auth->id)->delete()) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }
}
